package im.composer.ds;

import java.io.Closeable;
import java.util.Spliterator;
import java.util.function.Consumer;

import org.jaudiolibs.audioservers.AudioConfiguration;
import org.tritonus.share.sampled.FloatSampleBuffer;

import im.composer.audio.engine.BufferPlugin;

public class AudioStream implements Spliterator<FloatSampleBuffer>, BufferPlugin,Closeable {

	private final FloatSampleQueue q = new FloatSampleQueue();
	private final Object lock = new Object();
	private boolean closed = false;

	@Override
	public boolean tryAdvance(Consumer<? super FloatSampleBuffer> action) {
		while (!closed) {
			synchronized (lock) {
				while (!q.hasNext() && !closed) {
					try {
						lock.wait();
					} catch (InterruptedException e) {
						continue;
					}
				}
				FloatSampleBuffer buf = q.next();
				action.accept(buf);
			}
			return true;
		}
		return false;
	}

	@Override
	public Spliterator<FloatSampleBuffer> trySplit() {
		return null;
	}

	@Override
	public long estimateSize() {
		return Long.MAX_VALUE;
	}

	@Override
	public int characteristics() {
		return IMMUTABLE;
	}

	@Override
	public void bufferReceived(FloatSampleBuffer buf, long time) {
		synchronized (lock) {
			q.offer(buf);
			lock.notifyAll();
		}
	}

	@Override
	public void close() {
		synchronized (lock) {
			closed = true;
			lock.notifyAll();
		}
	}

	@Override
	public void configure(AudioConfiguration context) {

	}

}
